package ejb;

import java.util.Calendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import model.Notification;
import model.User;

@Singleton
@Startup
@LocalBean
public class TimerAnniversaire {
	/** TIMER **/
	@Resource
	TimerService timerService;
	
	//private Facade facade; 
	
	public TimerAnniversaire(){
		//facade = new FacadeBean();
	}
	
	@PostConstruct
	public void creerTimer() {
		System.out.println("CONSTRUCTION");
		ScheduleExpression scheduleExp = new ScheduleExpression().second("*/10").minute("*").hour("*");
		Timer timer = timerService.createCalendarTimer(scheduleExp);
	}
	
	@Timeout
	public void executerTraitement(Timer timer) {
		Context ctx;
		Facade facade = null;
		try {
			ctx = new InitialContext();
			facade = (Facade) ctx.lookup("java:module/FacadeBean");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar date = Calendar.getInstance();
		date.add(Calendar.DAY_OF_MONTH, 15);
		List<User> listUser = facade.getAllUser();
		for( User u : listUser ){
			if( u.getBirthday().get(Calendar.MONTH) == date.get(Calendar.MONTH) && 
					u.getBirthday().get(Calendar.DAY_OF_MONTH) == date.get(Calendar.DAY_OF_MONTH) ){
				for( User user : u.getFriends()){
					Notification n = new Notification();
					n.setIdPosteur(u.getIdUser());
					n.setIdReceveur(user.getIdUser());
					n.setMessage("fete son anniversaire dans 15 jours !");
					facade.addNotification(n);
				}
			}
		}
		System.out.println("Execution du traitement toutes les 10 secondes ");
	}
}
